package com.framework.projectframework.plugin.web.result;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 列表接口返回类
 *
 * @author zhang.shushan
 * @date 2018/12/7
 */
@Data
@Slf4j
public class ApiListResult<O, T> extends ApiResult<O> {

    public PageResult<List<T>> success(IPage<O> page, String orderBy, Boolean isAsc, Class<T> voClass) {
        List<T> list = page.getRecords().stream().map(o -> {
            try {
                T t = voClass.newInstance();
                BeanUtils.copyProperties(o, t);
                return t;
            } catch (InstantiationException | IllegalAccessException e) {
                log.error(e.getMessage(), e);
            }
            return null;
        }).collect(Collectors.toList());
        return new PageResult<List<T>>().success(list, page.getTotal(), page.getCurrent(), page.getSize(), page.getPages(), orderBy, isAsc);
    }

    public ApiResult<List<T>> success(IPage<O> page, Class<T> voClass) {
        return success(page, null, null, voClass);
    }
}
